package _2观察者模式.推数据方式;

import java.util.ArrayList;

class ConcreteSubject implements Subject {
    private final ArrayList<Observer> observerList;   // 存放观察者列表
    private Boolean changed;
    private Object message;                     // 被观察的具体信息

    ConcreteSubject() {
        observerList = new ArrayList<>();
        changed = false;
        message = "";
    }

    @Override
    public void addObserver(Observer observer) {
        if (!observerList.contains(observer)) {
            this.observerList.add(observer);
        }
    }

    @Override
    public void deleteObserver(Observer observer) {
        if (observerList.contains(observer)) {
            this.observerList.remove(observer);
        }
    }

    @Override
    public void notifyObserver() {
        if (changed) {
            for (Observer observer : observerList) {
                observer.update(message);
            }
        } else {
            System.out.println("没有新信息，不需要通知");
        }
    }

    // 更新
    public void pushNewMessage(Object newMessage) {
        if (!this.message.equals(newMessage)) {
            this.message = newMessage;
            changed = true;
        } else {
            System.out.println("没有信息需要更新");
            changed = false;
        }
    }
}

class ConcreteObserver implements Observer {

    @Override
    public void update(Object message) {
        System.out.println("接收者收到新信息：" + message);
    }
}

public class Demo01 {

    public static void main(String[] args) {
        ConcreteSubject subject = new ConcreteSubject();
        Observer observer1 = new ConcreteObserver();
        Observer observer2 = new ConcreteObserver();
        subject.addObserver(observer1);
        subject.addObserver(observer2);
        subject.pushNewMessage("腾讯招聘10个java后端开发实习生");
        subject.notifyObserver();
        subject.deleteObserver(observer2);
        subject.pushNewMessage("阿里招聘20个web后端开发实习生");
        subject.notifyObserver();
    }
}

